package com.kggs.springsnmp;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.PDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : fjc.dane@gmail.com
 * @createtime : 2021/8/19 16:28
 */
public class Snmp4Uitl {
    private static final Logger log = LoggerFactory.getLogger(Snmp4Uitl.class);

    public static void main(String[] args) throws IOException {
        //ord aPublic 1.3.6.1.2.1.25.3.3.1.2  10.253.46.140 10.243.141.114
        getChildIndicatorList("localhost", IndicatorOIDName.PHY_MEM_USE_PERCENT);
    }

    /***
     * @Date:  @Auth:xinsen.liao @Desc(V1.06): 获取磁盘内存指标
     */
    public static void getChildIndicatorList(String ip, IndicatorOIDName indicatorOIDName) throws IOException {

        List<TableEvent> aPublic = getTable(ip, indicatorOIDName.getOid().split(","), "public");
//        System.out.println(JSON.toJSONString(aPublic));
        for (TableEvent event : aPublic) {
            OID oid = event.getIndex();
            Integer index = oid.get(0);
            VariableBinding[] valueBinds = event.getColumns();
            Variable value = null;
            if (valueBinds.length > 0) {
                VariableBinding binding = valueBinds[0];
                value = valueBinds[0].getVariable();
            }

            if (value != null) {
                switch (indicatorOIDName.getName()) {
                    case "cpuRate":
                    case "upStream":
                    case "downStream":
                    case "streamSum":
                        System.out.println("=====>index：" + index);
                        System.out.println("=====>" + indicatorOIDName.getOid());

                        break;
                    case "networkInterface":
                    case "diskUseRate":
                        if (value.toString().toUpperCase().indexOf("MEMORY") >= 0) {
                            continue;
                        }
                        if (value != null)
                            System.out.println("=====>value：" + value.toString());
                        System.out.println("=====>" + indicatorOIDName.getOid());
                        break;
                    case "phyMemUsePercent":
                        System.out.println("=====>value：" + value.toString());
                        //System.out.println("=====>" + indicatorOIDName.getOid());
                        break;
                }
            }
        }
    }

    public static PDU send(String ip, String oid, String community) throws IOException {
        TransportMapping<UdpAddress> transportMapping = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transportMapping);
        try {
            snmp.listen();
            ResponseEvent response = null;
            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID(oid)));
            pdu.setType(PDU.GET);
            String address = ip + "/" + 161;
            Address targetAddress = new UdpAddress(address);
            CommunityTarget target = new CommunityTarget();
            target.setCommunity(new OctetString(community)); // 改字符串是我们在上面配置的
            target.setAddress(targetAddress);
            target.setRetries(2);
            target.setTimeout(3000);
            target.setVersion(SnmpConstants.version2c);
            response = snmp.get(pdu, target);
            PDU result = response.getResponse();
            if (result == null) {
                throw new RuntimeException("连接失败" + address + "  community:" + community);
            }
            return result;
        } catch (Exception ex) {
            throw ex;
        } finally {
            snmp.close();
        }
    }

    public static List<TableEvent> getTable(String ip, String[] oids, String community) throws IOException {
        TransportMapping transport = null;
        Snmp snmp = null;
        CommunityTarget target;
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);//创建snmp
            snmp.listen();//监听消息
            target = new CommunityTarget();
            target.setCommunity(new OctetString(community));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:" + ip + "/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }

                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            return list;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (transport != null)
                    transport.close();
                if (snmp != null)
                    snmp.close();
            } catch (IOException e) {
                log.error("Snmp4Uitl[]getTable[]error", e);
            }
        }
    }
}
